package com.jin.spirng_boot_learn.controllers;


import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

@RestController
@RequestMapping("test")
public class BasicController {

    @GetMapping(value = "request-param")
    public String requestParamController(@RequestParam(name = "NO", defaultValue = "0") Integer no) {
        return "{\"hello+\":\"world\"}";
    }


    @GetMapping(value = "upper")
    public String upperController(@RequestParam(name = "Upper", required = false) String upper) {
        System.out.println(upper);
        return "{\"hello+\":\"world\"}";
    }

    @PostMapping(value = "instream")
    public String uploadController(HttpServletRequest request, HttpServletResponse response) {

        try {
            ServletInputStream in = request.getInputStream();
            try {
                StreamUtils.copyToString(in, Charset.defaultCharset());
            } catch (NullPointerException ex) {
                // ignore, see SPR-13620
            } finally {
                try {
                    in.close();
                } catch (Throwable ex) {
                    // ignore, see SPR-12999
                }
            }
        } catch (FileNotFoundException ex) {
            // ignore, see SPR-12999
        } catch (IOException e) {

        }

        return "{\"hello+\":\"world\"}";
    }
}
